import { createRouter, createWebHashHistory } from "vue-router";
import HomePage from "@/views/Home/HomePage.vue";

const routes = [
  {
    path: "/",
    component: HomePage,
    name: "home",
  },
  {
    path: "/cart",
    component: () =>
      import(/* webpackChunkName:"cart123" */ "@/views/Cart/Cart.vue"),
    name: "cart",
  },
  {
    path: "/search",
    component: () =>
      import(/* webpackChunkName:"search123" */ "@/views/Search/Search.vue"),
    name: "search",
  },
  {
    path: "/searchList",
    component: () =>
      import(
        /* webpackChunkName:"searchList123" */ "@/views/SearchList/SearchList.vue"
      ),
    name: "searchList",
  },
  {
    path: "/orderList",
    component: () =>
      import(
        /* webpackChunkName:"orderList123" */ "@/views/OrderList/OrderList.vue"
      ),
    name: "orderList",
  },
  {
    path: "/orderconfirmation/:id",
    component: () =>
      import(
        /* webpackChunkName:"orderConfirm123" */ "@/views/OrderConfirmation/OrderConfirmation.vue"
      ),
    name: "orderconfirmation",
  },
  {
    path: "/my",
    component: () => import(/* webpackChunkName:"my123" */ "@/views/My/My.vue"),
    name: "my",
  },
  {
    path: "/address",
    component: () =>
      import(
        /* webpackChunkName:"address" */ "@/views/AddressEdit/AddressEdit.vue"
      ),
    name: "address",
  },
  {
    path: "/addressmanage",
    component: () =>
      import(
        /* webpackChunkName:"addressmanage" */ "@/views/AddressManage/AddressManage.vue"
      ),
    name: "addressmanage",
  },
  {
    path: "/addressselect",
    component: () =>
      import(
        /* webpackChunkName:"addressselect" */ "@/views/AddressSelect/AddressSelect.vue"
      ),
    name: "addressselect",
  },
  {
    path: "/login",
    component: () =>
      import(/* webpackChunkName:"login123" */ "@/views/Login/Login.vue"),
    name: "login",
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage;
      isLogin ? next({ name: "home" }) : next();
    },
  },
  {
    path: "/register",
    component: () =>
      import(/* webpackChunkName:"regi123" */ "@/views/Register/Register.vue"),
    name: "register",
  },
  {
    path: "/shop/:id",
    component: () =>
      import(/* webpackChunkName:"shop123" */ "@/views/Shop/Shop.vue"),
    name: "shop",
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage;
  const { name } = to;
  const isLoginOrRegister = name === "login" || name === "register";
  isLogin || isLoginOrRegister ? next() : next({ name: "login" });
});

export default router;
